package com.qian.fmall.service.impl;

import com.qian.fmall.pojo.ProductVo;
import com.qian.fmall.search.service.SearchInterface;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@DubboService
public class SearchServiceImpl implements SearchInterface {
    private String index="product-index";
    private String type="product-type";
    @Resource
    private RestHighLevelClient client;
    @Override
    public List<ProductVo> getProductVo(String keyword) {
        ArrayList<ProductVo> list = new ArrayList<>();
        SearchRequest req = new SearchRequest(index);
        req.types(type);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchQuery("productName",keyword));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("productName").preTags("<font color='red'>")
                .postTags("</font>");
        builder.highlighter(highlightBuilder);
        req.source(builder);
        try {
            SearchResponse search = client.search(req, RequestOptions.DEFAULT);
            SearchHit[] hits = search.getHits().getHits();
            for (SearchHit hit : hits) {
                ProductVo productVo = new ProductVo();
                Map<String, Object> map = hit.getSourceAsMap();
                Map<String, HighlightField> high = hit.getHighlightFields();
                HighlightField productName = high.get("productName");
                Text[] text = productName.getFragments();
                productVo.setProductId(hit.getId());
                if(map.get("price")!=null)
                {
                    productVo.setPrice(Double.parseDouble(map.get("price").toString()));
                }
                if(map.get("productImg")!=null)
                {
                    productVo.setProductImg(map.get("productImg").toString());
                }
                productVo.setSoldNum(Integer.parseInt(map.get("soldNum").toString()));
                productVo.setProductName(text[0].toString());
                list.add(productVo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
